<template>
  <div class="contract-edit-container">
    <div class="section-title">编辑签约信息</div>

    <el-card class="form-card">
      <div class="section-subtitle">居民信息</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" class="form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="姓名"  prop="name" required>
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证号" prop="idCard" required>
              <el-input v-model="form.idCard" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="gender" required>
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出生年月" prop="birthdate" required>
              <el-date-picker v-model="form.birthdate" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="phone" required>
              <el-input v-model="form.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="现居地">
              <el-input v-model="form.address" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="居民标签">
              <el-select
                  v-model="form.tags"
                  placeholder="请选择"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  style="width: 100%"
              >
                <el-option
                    v-for="item in tags"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
    </el-card>

    <el-card class="form-card">
      <div class="section-subtitle">签约信息</div>
      <el-form :model="form"  ref="formRef" :rules="rules" label-width="100px" class="form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="签约编号">
              <span>{{ form.id }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签约状态">
              <el-tag :type="getTagType(form.status)">
                {{ getStatusName(form.status) }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签约机构" required>
              <el-select ref="sel1" v-model="form.inst" placeholder="请选择" @change="aa">
                <el-option
                    v-for="item in organizations"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="签约团队" required>
              <el-select v-model="form.team" placeholder="请选择">
                <el-option
                    v-for="item in teams"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="签约医生" required>
              <el-select v-model="form.doctor" placeholder="请选择">
                <el-option
                    v-for="item in doctors"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="服务包" required>
              <el-select v-model="form.packageId" placeholder="请选择" >
              <el-option
                  v-for="item in packages"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  />

              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="签约类型">
              <span>{{ form.type }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="签约周期">
              <span>{{ form.signCycle }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="申请时间">
              <span>{{ formatDateTime(form.applyTime) }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="生效日期" prop="effectiveDate" required>
              <el-date-picker v-model="form.effectiveDate" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="费用">
              <span>￥{{ form.fee }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="签约备注" class="full-width">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
      </el-form>

    </el-card>

    <div class="form-footer">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref} from "vue";
import {useRoute , useRouter} from "vue-router";
import axios from "axios";
import {ElMessage} from "element-plus";

const route = useRoute();
const id = ref(route.params.id);
const router = useRouter();

const sel1 = ref(null);

// ==================== 状态映射配置 ====================
// 数字状态ID到中文状态名的映射
const STATUS_MAP = {
  1: '待审核',
  2: '待服务', 
  3: '已驳回',
  4: '待支付',
  5: '生效中',
  6: '已过期'
};

// 中文状态名到数字ID的反向映射
const STATUS_NAME_TO_ID = {
  '待审核': 1,
  '待服务': 2, 
  '已驳回': 3,
  '待支付': 4,
  '生效中': 5,
  '已过期': 6
};

// 状态对应的标签颜色配置
const STATUS_TAG_MAP = {
  1: 'primary',   // 待审核 - 蓝色
  2: 'success',   // 待服务 - 绿色
  3: 'danger',    // 已驳回 - 红色
  4: 'warning',   // 待支付 - 橙色
  5: 'success',   // 生效中 - 绿色
  6: 'info'       // 已过期 - 灰色
};

// ==================== 响应式数据 ====================
const form = ref({
  tags: [],
});

// 下拉选项数据
const organizations = ref([]); // 签约机构列表
const teams = ref([]);         // 医生团队列表
const packages = ref([]);      // 服务包列表
const tags = ref([]);          // 居民标签列表
const doctors = ref([]);       // 医生列表

// ==================== 工具函数 ====================
/**
 * 时间格式化函数 - 格式：YYYY-MM-DD HH:mm:ss
 * @param {string} isoString - ISO格式的时间字符串
 * @returns {string} 格式化后的时间字符串
 */
const formatDateTime = (isoString) => {
  if (!isoString) return '';
  const date = new Date(isoString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1)
      .padStart(2, '0')}-${String(date.getDate())
      .padStart(2, '0')} ${String(date.getHours())
      .padStart(2, '0')}:${String(date.getMinutes())
      .padStart(2, '0')}:${String(date.getSeconds())
      .padStart(2, '0')}`;
};

/**
 * 处理标签选择变化
 * @param {number} tagId - 标签ID
 */
const handleTagChange = (tagId) => {
  const index = form.value.tags.indexOf(tagId);
  if (index === -1) {
    form.value.tags.push(tagId);
  } else {
    form.value.tags.splice(index, 1);
  }
};

const aa = (value)=>{
  //alert(value)
}

/**
 * 加载下拉选项数据
 */
const loadOptions = () => {
  // 加载签约机构列表
  axios.get('/institution/getInstitution').then(resp => {
    organizations.value = resp.data;

  })

  // 加载医生团队列表
  axios.get('/team/getAllTeam').then(resp => {
    teams.value = resp.data;
  });

  // 加载服务包列表
  axios.get('/package/getAllPackage').then(resp => {
    packages.value = resp.data;
  });
  
  // 加载居民标签列表
  axios.get(`/tag/getAllTag`).then(resp => {
    tags.value = resp.data;
  })
  
  // 加载医生列表
  axios.get(`/doctors/getAllDoctors`).then(resp => {
    doctors.value = resp.data;
  })
};

// ==================== 数据初始化 ====================
/**
 * 初始化编辑页面数据
 * 从后端获取合同详情信息并填充表单
 */
const initData = async () => {
  try {
    const response = await axios.get(`/contract/getAllContractDetail/${id.value}`);

    if (response.data && response.data.length > 0) {
      // 合并多条记录中的标签字段
      const tagList = response.data.map(r => r.tag).filter(Boolean);
      const uniqueTags = [...new Set(tagList)];

      // 使用第一条记录作为主数据源
      let contractData = { ...response.data[0], tags: uniqueTags };

      // 处理status字段 - 统一转换为数字ID格式
      if (contractData.contractStatus !== undefined && contractData.contractStatus !== null) {
        const originalStatus = contractData.contractStatus;

        if (typeof originalStatus === 'string') {
          if (STATUS_NAME_TO_ID[originalStatus]) {
            contractData.contractStatus = STATUS_NAME_TO_ID[originalStatus];
          } else {
            contractData.contractStatus = parseInt(originalStatus);
            if (isNaN(contractData.contractStatus)) {
              contractData.contractStatus = 1; // 默认为待审核
            }
          }
        } else if (typeof originalStatus === 'number') {
          contractData.contractStatus = originalStatus;
        } else {
          contractData.contractStatus = parseInt(originalStatus);
          if (isNaN(contractData.contractStatus)) {
            contractData.contractStatus = 1; // 默认为待审核
          }
        }
      } else {
        contractData.contractStatus = 1; // 默认为待审核
      }

      form.value = contractData;
      console.log(form.value.inst+"=================");
    }
  } catch (error) {
    ElMessage.error('获取签约详情失败，请重试');
  }
}




/**
 * 返回上一页
 */
const handleBack = () => {
  router.back();
};

/**
 * 保存签约信息
 */
const handleSave = () => {

  axios.post('/contract/addContract',form.value).then(resp => {
      ElMessage.success(resp.data);
      initData();
  })
}

// ==================== 状态处理函数 ====================
/**
 * 获取状态显示名称
 * @param {string|number} statusId - 状态ID
 * @returns {string} 状态中文名称
 */
const getStatusName = (statusId) => {
  let normalizedStatusId = statusId;
  
  if (typeof statusId === 'string') {
    if (STATUS_NAME_TO_ID[statusId]) {
      normalizedStatusId = STATUS_NAME_TO_ID[statusId];
    } else {
      normalizedStatusId = parseInt(statusId);
    }
  }
  
  return STATUS_MAP[normalizedStatusId] || '未知状态';
};

/**
 * 获取状态标签颜色类型
 * @param {string|number} statusId - 状态ID
 * @returns {string} Element Plus 标签类型
 */
const getTagType = (statusId) => {
  let normalizedStatusId = statusId;
  
  if (typeof statusId === 'string') {
    if (STATUS_NAME_TO_ID[statusId]) {
      normalizedStatusId = STATUS_NAME_TO_ID[statusId];
    } else {
      normalizedStatusId = parseInt(statusId);
    }
  }
  
  return STATUS_TAG_MAP[normalizedStatusId] || 'info';
};

// ==================== 表单验证 ====================
const formRef = ref(null);

// 表单验证规则配置
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{15}$|^\d{17}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthdate: [{ required: true, message: '请选择出生年月', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入现居地', trigger: 'blur' }],
  inst: [{ required: true, message: '请选择签约机构', trigger: 'change' }],
  team: [{ required: true, message: '请选择签约团队', trigger: 'change' }],
  doctor: [{ required: true, message: '请选择签约医生', trigger: 'change' }],
  packageId: [{ required: true, message: '请选择服务包', trigger: 'change' }],
  effectiveDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
};



onMounted(async () => {
  await initData();
  loadOptions();
});




</script>

<style scoped>
/* === 多选下拉复选框视觉增强样式 === */
/* 每项强制显示复选框的方框 */
.el-select-dropdown__item {
  display: flex;
  align-items: center;
}

/* 未选中项的方框 */
.el-select-dropdown__item::before {
  content: "";
  width: 14px;
  height: 14px;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  margin-right: 8px;
  display: inline-block;
  box-sizing: border-box;
}

/* 已选中项，显示对勾 ✔ 并改变背景色 */
.el-select-dropdown__item.is-selected::before {
  background-color: #409EFF;
  color: white;
  text-align: center;
  line-height: 14px;
  font-size: 12px;
  content: "✔";
}

/* === 你原有的样式保留如下 === */
.el-select-dropdown .el-checkbox__input {
  width: 18px;
  height: 18px;
}

.el-select-dropdown .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409EFF;
  border-color: #409EFF;
}

.contract-edit-container {
  background-color: #fff;
  padding: 30px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  text-align: left;
}

.section-subtitle {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0 20px;
  text-align: left;
}

.form-card {
  margin-bottom: 30px;
}

.form-footer {
  text-align: left;
  margin-top: 20px;
}

.full-width {
  width: 100%;
}

.family-card-container {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 20px;
}

.family-card {
  width: 160px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.family-card:hover {
  border-color: #409EFF;
}

.family-info {
  display: flex;
  gap: 10px;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
}

.relation {
  font-size: 12px;
  color: #888;
}

.add-member {
  color: #409EFF;
  cursor: pointer;
  margin-left: 10px;
}
</style>

